/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.servlets;

import com.docmosis.SystemManager;
import com.docmosis.document.DocumentProcessor;
import com.docmosis.document.ProcessingException;
import com.docmosis.document.converter.ConversionException;
import com.docmosis.document.converter.ConversionFormat;
import com.docmosis.document.converter.ConversionInstruction;
import com.docmosis.document.converter.NoConvertersRunningException;
import com.docmosis.document.converter.pool.ConverterPoolException;
import com.docmosis.template.TemplateStoreException;
import com.docmosis.template.population.Cleanable;
import com.docmosis.template.population.DataProvider;
import com.docmosis.template.population.DataProviderBuilder;
import com.docmosis.template.store.DropStoreHelper;
import com.docmosis.template.store.TemplateContext;
import com.docmosis.template.store.TemplateIdentifier;
import com.docmosis.template.store.TemplateStoreFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ipo.mm.ejb.entities.Document;
import org.ipo.mm.ejb.entities.Meeting;
import org.ipo.mm.ejb.entities.Representative;
import org.ipo.mm.ejb.facade.meeting.MeetingFacadeLocal;

/**
 *
 * @author predrag
 */
public class GetMeetingRaport extends HttpServlet {
    @EJB
    private MeetingFacadeLocal meetingFacade;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String meetingId = request.getParameter("mid");
        Integer meetingIdInteger = Integer.parseInt(meetingId);
        Meeting m = meetingFacade.findFetchDocs(meetingIdInteger);

        String fileName = "meeting-no" + m.getId()/* + (m.getEventName() != null ? m.getEventName() : "") + (m.getVenue() != null ? m.getVenue() : "")*/ + ".zip";

        //response.setContentType("text/html;charset=UTF-8");
        response.setContentType(getServletContext().getMimeType("reports.zip"));
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        

        ServletOutputStream out = response.getOutputStream();
        initDocmosis();
        DataProvider dp = prepareData(m);

        try {
            // load any templates in the current directory into the template store
            prepareTemplates();

            // run a single document render
            runRender(dp, out);



        } catch (Exception e){
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught: ", e.toString());
        }
        finally {
            out.close();
            // shutdown the system
            SystemManager.release();
            if (dp instanceof Cleanable) {
                ((Cleanable) dp).cleanup();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public static void initDocmosis() {
        //System.setProperty("docmosis.key", "XABE-ALYN-DICJ-KJER-C496");
        //System.setProperty("docmosis.document.converter.pool.config.resource","converterPoolConfig.xml");
        //System.setProperty("docmosis.openoffice.location","E:/Program Files/OpenOffice.org 3");

        try{
            // initialise the system based on configuration
            SystemManager.initialise();
        }
        catch(Exception e){
                  System.out.println(e.toString());
        }

        }
    

    public  DataProvider prepareData(Meeting m) {
        
        // load the data from something
//        Meeting m = new Meeting();
//        m.setActions("Mika|Treba da trci|14/4/2006\nPera|stvarno treba da trci|dokle moze");
//        m.setConclusion("Mikro je rekao nesto\nPedja je rekao nesto");
//        m.setDate(new Date());
//        m.setEventName("Izmisljeni sastanak");
//        m.setNote("Da dodam notu na ovaj sastanak :)");
//        Representative organi = new Representative();
//        organi.setFirstName("Predrag");
//        organi.setLastName("Milutinovic");
//        Institution inst = new Institution();
//        inst.setName("Neka ludilo institucija");
//        organi.setInstitution(inst);
//        m.setOrganizer(organi);
//        Vector<Representative> part = new Vector<Representative>();
//        part.add(organi);
//        part.add(organi);
//        m.setRepresentativeCollection(part);
//        m.setVenue("negde na divljem zapadu");


        DataProviderBuilder dpb = new DataProviderBuilder();
        if(m.getVenue()!=null){
        dpb.add("venue", m.getVenue());
        }
        if(m.getDate() != null){
        dpb.add("date", m.getDate().toString());
        }
        if(m.getEventName()!=null){
        dpb.add("event_name", m.getEventName());
        }
        if(m.getOrganizer()!=null){
        dpb.add("organizer", m.getOrganizer().getFirstName() + " " + m.getOrganizer().getLastName() + ", " + m.getOrganizer().getInstitution().getName());
        }
        int i = 0;

        //filling participants
        if (m.getRepresentativeCollection() != null) {
            for (Iterator it = m.getRepresentativeCollection().iterator(); it.hasNext();) {
                Representative p = (Representative) it.next();
                dpb.add("participants." + i + ".name", p.getFirstName() + " " + p.getLastName() + ", " + p.getInstitution().getName());
                i++;
            }
        }

        //filling minutes of meetings
        if (m.getConclusion() != null) {
            StringTokenizer minutes = new StringTokenizer(m.getConclusion(), "\n");
            i = 0;
            while (minutes.hasMoreTokens()) {
                dpb.add("minutes." + i + ".name", minutes.nextToken());
                i++;
            }
        }

        //filling actons
//        if (m.getActions() != null) {
//            StringTokenizer actions = new StringTokenizer(m.getActions(), "\n");
//            i = 0;
//            while (actions.hasMoreTokens()) {
//
//                String actionRow = actions.nextToken();
//                StringTokenizer actionrowTokenizer = new StringTokenizer(actionRow, "|");
//                dpb.add("actionRow." + i + ".name", actionrowTokenizer.nextToken());
//                dpb.add("actionRow." + i + ".action", actionrowTokenizer.nextToken());
//                dpb.add("actionRow." + i + ".date", actionrowTokenizer.nextToken());
//                i++;
//            }
//        }

        //filling files
        if (m.getDocumentCollection() != null) {
            i = 0;
            for (Iterator it = m.getDocumentCollection().iterator(); it.hasNext();) {
                Document d = (Document) it.next();
                dpb.add("files." + i + ".name", d.getName() + " " + d.getNote() + ", " + d.getFileName());
                i++;
            }
        }

        //filling note

        dpb.add("note", m.getNote());


        return dpb.getDataProvider();

    }

    private  void prepareTemplates()
            throws IOException, ConversionException, ConverterPoolException, TemplateStoreException, NoConvertersRunningException {
        DropStoreHelper storeHelper = new DropStoreHelper(TemplateStoreFactory.getStore());
        // /home/makcro/Download/ipoReportTemplate
        // /home/predrag/Documents/templates
        String templateFileName = getTemplateFileName(TEMPLATE_DIR_KEY);
        File f = new File(templateFileName);
        storeHelper.process(f, false);
        System.out.println("Template(s) loaded into store");
    }

    private  void runRender(DataProvider dp, OutputStream out)
            throws IOException, ConversionException, ConverterPoolException, TemplateStoreException, ProcessingException {
        System.out.println("Performing a test render");
        String templateFileName = getTemplateFileName(TEMPLATE_FILE_KEY);
        
        TemplateIdentifier templateId = new TemplateIdentifier(templateFileName,
                new TemplateContext(""));

        ConversionInstruction instruction = new ConversionInstruction();
        instruction.setConversionFormats(new ConversionFormat[]{
                    ConversionFormat.FORMAT_ODT,
                    ConversionFormat.FORMAT_WORD,
                    ConversionFormat.FORMAT_PDF,});
        instruction.setOutputFileName("meetingReport");
//        FileOutputStream streamTo = new FileOutputStream("reports.zip");
        try {
            long start = System.currentTimeMillis();
            DocumentProcessor.renderDoc(templateId, dp, instruction, out);
            System.out.println("newDocuments.zip generated in " + (System.currentTimeMillis() - start) + " milliseconds (including wait time)");
        } finally {
//            FileUtilities.close(streamTo);
        }
    }


    /*
     * utility method for loading template file name from properties file
     * /

     */
    private String getTemplateFileName(String key) throws FileNotFoundException, IOException{
        Properties props = new Properties();
        props.load(new FileInputStream(REPORTING_PROPERTIES_FILE_NAME));

        String filename = props.getProperty(key);
        return filename;
    }

    private final String REPORTING_PROPERTIES_FILE_NAME = "docmosis_reports.properties";
    private final String TEMPLATE_DIR_KEY = "templateDir";
    private final String TEMPLATE_FILE_KEY = "templateFile";
}